import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { AnswerService } from 'src/answer/answer.service';
import { QuestionService } from 'src/question/question.service';

@Injectable()
export class StatService {
  constructor(
    private readonly answerService: AnswerService,
    private readonly questionService: QuestionService,
  ) {}

  private async fuc(id: string) {
    try {
      // 1. 从问题服务获取组件列表
      const question = await this.questionService.findOne(id);
      const componentList = question?.componentList || [];

      // 2. 创建空对象用于存储答案
      const answerObj = {};
      componentList.forEach((item) => {
        answerObj[item.fe_id] = ''; // 初始化每个组件ID对应的值为空字符串
      });

      // 3. 从答案服务获取所有答案
      const answers = await this.answerService.getAll(id);
      const resultList: any[] = [];

      // 4. 组合数据
      answers.forEach((answerItem) => {
        answerItem.answerList.forEach((answer: any) => {
          if (answer.componentId in answerObj) {
            answerObj[answer.componentId] = answer.value; // 更新对应组件的值
          }
        });
        resultList.push({ ...answerObj }); // 将当前状态的对象加入结果列表
      });

      return resultList;
    } catch (err) {
      throw new HttpException(err.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async getAll(id: string) {
    return await this.fuc(id);
  }
}
